package com.zhiyou.app.shop.website.util;


import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.security.auth.kerberos.KerberosKey;
import javax.security.auth.kerberos.KerberosPrincipal;

public class EncryptData
{
  private static Key key = null;

  public static String encrypt(String encryptString)
    throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, UnsupportedEncodingException, IllegalBlockSizeException, BadPaddingException
  {
    Key key = getKey();
    Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
    byte[] by = encryptString.getBytes("utf8");
    cipher.init(1, key);
    byte[] cipherText = cipher.doFinal(by);
    return byte2hex(cipherText).replaceAll("\n", "");
  }

  
  public static Key getKey()
  {
    if (key == null)
    {
      String algorithm = "DES";
      String name = "zhiyou@km.com.cn";
      String password = "zhiyousoft";
      KerberosPrincipal kerberosPrincipal = new KerberosPrincipal(name);
      key = new KerberosKey(kerberosPrincipal, password.toCharArray(), algorithm);
    }
    return key;
  }

  public static String byte2hex(byte[] bytes)
  {
    StringBuffer retString = new StringBuffer();
    for (int i = 0; i < bytes.length; ++i) {
      retString.append(Integer.toHexString(256 + (bytes[i] & 0xFF)).substring(1));
    }
    return retString.toString();
  }

  public static byte[] hex2byte(String hexString)
  {
    if (hexString == null)
      return null;
    byte[] bts = new byte[hexString.length() / 2];
    for (int i = 0; i < bts.length; ++i) {
      bts[i] = (byte)Integer.parseInt(hexString.substring(2 * i, 2 * i + 2), 16);
    }
    return bts;
  }
  
  public static String decrypt(String decryptString)
		    throws NoSuchAlgorithmException, NoSuchPaddingException, UnsupportedEncodingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException
		  {
		    Key key = getKey();
		    Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
		    byte[] by = hex2byte(decryptString);
		    cipher.init(2, key);
		    byte[] cipherText = cipher.doFinal(by);
		    return new String(cipherText, "utf-8");
		  }

  
  public static void main(String[] args) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, UnsupportedEncodingException, IllegalBlockSizeException, BadPaddingException {
	  String s = EncryptData.encrypt("cn663164");
	  System.out.println(s);
	  System.out.println(EncryptData.decrypt("2bab05002bd999558783e6604e97c15b"));
  }
}